package com.jf.net.interceptor

import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * RequestInterceptor
 * @author JackyFlame
 * @time 2023/10/20 14:50
 * @description
 */
open class RequestInterceptor : Interceptor {

    private val customHeader = HashMap<String, String>()
    private val customQuery = HashMap<String, String>()

    fun clear() {
        this.customHeader.clear()
        this.customQuery.clear()
    }

    /**
     * 增加自定义header（若参数已存在则会被替换）
     * @param name
     * @param value
     * */
    fun addHeader(name: String, value: String) {
        this.customHeader[name] = value
    }

    /**
     * 增加自定义query参数（若参数已存在则会被替换）
     * @param name
     * @param value
     * */
    fun addQuery(name: String, value: String) {
        this.customQuery[name] = value
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        val urlBuilder = originalRequest.url.newBuilder()
        //add custom params
        addQueryParam(urlBuilder)
        //Header
        val newRequestBuilder = originalRequest.newBuilder()
        addHeaderParam(newRequestBuilder)
        //proceed
        return chain.proceed(newRequestBuilder.url(urlBuilder.build()).build())
    }

    /**
     * 执行增加自定义query参数（若参数已存在则替换）
     * @param urlBuilder
     * */
    open fun addQueryParam(urlBuilder: HttpUrl.Builder) {
        customQuery.forEach { (key, value) ->
            urlBuilder.setQueryParameter(key, value)
        }
    }

    /**
     * 执行增加自定义header（若参数已存在则替换）
     * @param newRequestBuilder
     * */
    open fun addHeaderParam(newRequestBuilder: Request.Builder) {
        newRequestBuilder
            .addHeader("Accept", "application/json;charset=utf-8")
            .addHeader("Accept-Language", "zh-CN")
        customHeader.forEach { (key, value) ->
            newRequestBuilder.header(key, value)
        }
    }

}